package com.iteaj.iboot.plugin.crawler.controller;

import com.iteaj.framework.result.BooleanResult;
import com.iteaj.framework.result.Result;
import com.iteaj.iboot.plugin.crawler.CrawlerProperties;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

import static com.iteaj.iboot.plugin.crawler.controller.SitesController.collectSiteMap;

/**
 * Selenium管理
 * @author iteaj
 * @since 2024-10-05
 */
@RestController
@RequestMapping("/crawler/selenium")
public class SeleniumController implements ApplicationListener<ApplicationReadyEvent>, DisposableBean {

    private Process start;
    private final CrawlerProperties properties;

    public SeleniumController(CrawlerProperties properties) {
        this.properties = properties;
    }

    /**
     * 打开浏览器
     * @return
     */
    @PostMapping("open")
    public synchronized Result<Boolean> open(Integer port) {
        if(start == null) {
            ProcessBuilder processBuilder = new ProcessBuilder(properties.getBasicPath() + properties.getChromeExec()
                    , "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36"
                    , "--disable-infobars"
                    , "--headless"
                    , "--enable-javascript"
                    , "--allow-file-access-from-files"
//                    , String.format("--load-extension=%s", "D:\\Program Data\\web\\extension\\test.crx")
                    , String.format("--remote-debugging-port=%d", properties.getDebuggingPort())
                    , String.format("--user-data-dir=%s%s", properties.getBasicPath(), properties.getUserDataDir())
                    , "https://www.baidu.com");

            try {
                start = processBuilder.start();
                start.onExit().handleAsync((process, e) -> {
                    start = null; collectSiteMap.clear(); return e;
                });
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return BooleanResult.buildTrue("开启成功");
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        try {
            new ProcessBuilder(properties.getBasicPath() + properties.getChromeExec()
                    , "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36"
                    , "--disable-infobars", "--enable-javascript", "--allow-file-access-from-files", "--headless"
    //                    , String.format("--load-extension=%s", "D:\\Program Data\\web\\extension\\test.crx")
                    , String.format("--remote-debugging-port=%d", properties.getDebuggingPort())
                    , String.format("--user-data-dir=%s%s", properties.getBasicPath(), properties.getUserDataDir())
                    , properties.getUrl()).start();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

//        URL resource = getClass().getClassLoader().getResource("chromedriver.exe");
//        File file = new File(resource.getFile());
//        Logger.getLogger("org.openqa.selenium.chrome").setLevel(Level.ALL);
//
//        ChromeOptions options = new ChromeOptions();
//        options.setBinary(properties.getBasicPath() + properties.getChromeExec());
//        options.addArguments("--disable-infobars"); // 去掉信息栏
//        options.addArguments("--user-data-dir="+properties.getBasicPath() + properties.getUserDataDir());
//        options.addArguments("--no-sandbox");
//        options.addArguments("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36");
//        options.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"}); // 去掉被控制的提示
//        File extension = new File("D:\\Program Data\\web\\extension\\test.crx");
//        options.addExtensions(extension);
//        ChromeDriverService driverService = new ChromeDriverService.Builder()
//                .usingDriverExecutable(file).build();
//        ChromeDriver driver = new ChromeDriver(driverService, options);
//
//        driver.manage().window().maximize();
//        driver.get(properties.getUrl());
    }

    @Override
    public void destroy() throws Exception {
//        if(d)
    }
}
